package space.edge.d.demo.qrcode;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.widget.TextView;
import android.widget.Toast;

import space.edge.d.demo.qrcode.codescanner.utils.PermissionChecker;
import space.edge.d.demo.qrcode.common.Result;
import space.edge.d.demo.qrcode.codescanner.scanner.CameraPreview;
import space.edge.d.demo.qrcode.codescanner.ui.HollowView;

/**
 * Created by gsl on 2017/10/28.
 * 预览Activity
 */

public class PreviewActivity extends Activity {

    private final String[] PERMISSIONS = new String[]{Manifest.permission.CAMERA};

    private CameraPreview mCameraPreview;
    private HollowView mHollowView;
    private TextView mTv;

    private Rect hollowRect;
    private boolean permissionGranted;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preview);
        mCameraPreview = findViewById(R.id.v_preview);
        mHollowView = findViewById(R.id.hollow_view);
        mTv = findViewById(R.id.tv_result);
        checkPermission();
        mHollowView.post(new Runnable() {
            @Override
            public void run() {
                setFramingRect();
            }
        });
    }

    private void setFramingRect() {
        hollowRect = mHollowView.getHollowRect();
        int previewW = mCameraPreview.getMeasuredWidth();
        int previewH = mCameraPreview.getMeasuredHeight();
        int hollowW = mHollowView.getMeasuredWidth();
        int hollowH = mHollowView.getMeasuredHeight();
        int verticalOffset = (previewH - hollowH) / 2;
        int horizontalOffset = (previewW - hollowW) / 2;
        hollowRect.offset(horizontalOffset, verticalOffset);

        mHollowView.startScan();
        mCameraPreview.setFramingRect(hollowRect);

        resume();
    }

    private void checkPermission() {
        if (PermissionChecker.checkPermission(this, PERMISSIONS)) {
            permissionGranted = true;
        } else {
            permissionGranted = false;
            ActivityCompat.requestPermissions(this, PERMISSIONS, 0);
        }
    }

    private boolean allPermissionGranted(int[] grantResults) {
        for (int grant : grantResults) {
            if (grant == PackageManager.PERMISSION_DENIED)
                return false;
        }
        return true;
    }

    private void resume() {
        if (permissionGranted) {
            if (mCameraPreview.getState() == CameraPreview.STATE_RESUMED)
                return;
            mCameraPreview.resume();
            mCameraPreview.setCallback(new ScannerCallback());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 0) {
            if (!allPermissionGranted(grantResults)) {
                finish();
                return;
            }
            permissionGranted = true;
            if (hollowRect != null)
                resume();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (hollowRect != null) {
            resume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mCameraPreview.pause();
    }

    private int i = 0;

    private class ScannerCallback implements CameraPreview.ScannerCallback {

        @Override
        public void onSuccess(Result result) {
            String text = result.getText();
            if (!TextUtils.isEmpty(text))
                mTv.setText(text);
            i++;
            Toast.makeText(PreviewActivity.this, "第" + i + "尝试，扫码成功", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFail() {
            i++;
        }
    }

    public static Intent newIntent(Context context) {
        return new Intent(context, PreviewActivity.class);
    }
}
